<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="vBillNo">
        <el-input
          v-model="queryParams.vBillNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="vOpr">
        <el-input
          v-model="queryParams.vOpr"
          placeholder="请输入执行人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据时间">
        <el-date-picker
          v-model="daterangeDBegin"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.inv_stock_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockbillList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" align="center" prop="vBillNo" />
      <el-table-column label="仓库iD" align="center" prop="vWHId" />
      <el-table-column label="库区" align="center" prop="vAreaId" />
      <el-table-column label="库位" align="center" prop="vLocationId" />
      <el-table-column label="执行人" align="center" prop="vOpr" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="dBegin"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dBegin, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="dEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dEnd, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.inv_stock_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleStatusupdate(scope.row, '01')"
            v-if="scope.row.status == '00'"
            >开始盘点</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleStatusupdate(scope.row, '02')"
            v-if="scope.row.status == '01'"
            >完成盘点</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleStatusupdate(scope.row, '03')"
            v-if="scope.row.status == '02' || scope.row.status == '04'"
            >提交批复</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改盘点单信息对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="70%" append-to-body>
      <div class="drawer-container">
        <div class="xin-main">
          <div class="xin-content" style="height: 90%">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="单据编号" prop="vBillNo">
                    <el-input
                      v-model="form.vBillNo"
                      placeholder="请输入单据编号"
                      disabled="true"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="执行人" prop="vOpr">
                    <el-input v-model="form.vOpr" placeholder="请输入执行人" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="账面日期" prop="dBegin">
                    <el-date-picker
                      clearable
                      v-model="form.dBegin"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择账面日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="盘点日期" prop="dEnd">
                    <el-date-picker
                      clearable
                      v-model="form.dEnd"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择盘点日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="仓库" prop="vWHId">
                    <el-select
                      v-model="form.vWHId"
                      placeholder="请选择"
                      clearable
                      @change="handleWHEdit"
                    >
                      <el-option
                        v-for="dict in whList"
                        :key="dict.id"
                        :label="dict.vWHName"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="库区" prop="vAreaId">
                    <el-select
                      v-model="form.vAreaId"
                      placeholder="请选择"
                      clearable
                      @change="handleAreaEdit"
                    >
                      <el-option
                        v-for="dict in areaList"
                        :key="dict.id"
                        :label="dict.vWHName"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="库位" prop="vLocationId">
                    <el-select
                      v-model="form.vLocationId"
                      placeholder="请选择"
                      clearable
                      multiple
                    >
                      <el-option
                        v-for="dict in localtionList"
                        :key="dict.id"
                        :label="dict.vWHName"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col> -->
              </el-row>
              <el-row>
                <el-col :span="16"></el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      size="mini"
                      @click="addSpaList()"
                      >生成物料清单</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider content-position="left"></el-divider>
            <el-table min-height="450px" border :data="itemList">
              <el-table-column
                label="物料名称"
                align="center"
                prop="vSpaName"
              />
              <el-table-column
                label="规格型号"
                align="center"
                prop="vSpaModel"
              />
              <el-table-column label="品牌" align="center" prop="vSpaBrand" />
              <el-table-column label="系统库存" align="center" prop="nInvQty" />
              <el-table-column
                label="异动数量"
                align="center"
                prop="nChangeQty"
              />
              <el-table-column
                label="实盘数量"
                align="center"
                prop="nActualQty"
              >
                <template slot-scope="scope">
                  <el-input
                    size="small"
                    v-model="scope.row.nActualQty"
                    @change="handleEdit(scope.$index, scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="盘点盈亏" align="center" prop="nYKQty">
                <template slot-scope="scope">
                  {{ getNYkQty(scope.row) }}</template
                >
              </el-table-column>
              <el-table-column label="仓库" align="center" prop="vWhName" />
              <el-table-column label="库区" align="center" prop="vAreaName" />
              <el-table-column
                label="库位"
                align="center"
                prop="vLocationName"
              />
              <el-table-column label="备注" align="center" prop="remark">
                <template slot-scope="scope">
                  <el-input size="small" v-model="scope.row.remark"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div
              class="xin-footer"
              style="position: fixed; bottom: 5px; right: 10px"
            >
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button>取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listStockbill,
  viewById,
  delStockbill,
  addStockbill,
  updateStockbill,
  getInvDataList,
  updateBillStatus,
} from "@/api/inv/inv0006";
import { listInv0001 } from "@/api/inv/inv0001";
import { getToken } from "@/utils/auth";
export default {
  name: "Stockbill",
  dicts: ["inv_stock_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点单信息表格数据
      stockbillList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 库位时间范围
      daterangeDBegin: [],
      // 库位时间范围
      daterangeDEnd: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vBillNo: null,
        vWHId: null,
        vOpr: null,
        dBegin: null,
        dEnd: null,
        status: null,
        vAreaId: null,
        vLocationId: null,
      },
      itemList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vWHId: [
          { required: true, message: "仓库iD不能为空", trigger: "change" },
        ],
        vAreaId: [
          { required: true, message: "库区不能为空", trigger: "change" },
        ],
        dBegin: [
          { required: true, message: "账面日期不能为空", trigger: "change" },
        ],
        dEnd: [
          { required: true, message: "盘点日期不能为空", trigger: "change" },
        ],
      },
      whList: [],
      localtionList: [],
      areaList: [],
      currentDate: "",
    };
  },
  created() {
    this.getList();
    this.getCurrentDate();
    this.getWH();
  },
  methods: {
    /** 查询盘点单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDBegin && "" != this.daterangeDBegin) {
        this.queryParams.params["beginDBegin"] = this.daterangeDBegin[0];
        this.queryParams.params["endDBegin"] = this.daterangeDBegin[1];
      }
      if (null != this.daterangeDEnd && "" != this.daterangeDEnd) {
        this.queryParams.params["beginDEnd"] = this.daterangeDEnd[0];
        this.queryParams.params["endDEnd"] = this.daterangeDEnd[1];
      }
      listStockbill(this.queryParams).then((response) => {
        this.stockbillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vBillNo: null,
        vWHId: null,
        vOpr: this.$store.state.user.name,
        dBegin: this.currentDate,
        dEnd: this.currentDate,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: "00",
        vAreaId: null,
        vLocationId: null,
      };
      this.resetForm("form");
      this.itemList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDBegin = [];
      this.daterangeDEnd = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加盘点单信息";
      listInv0001({ parentId: "0", whType: "L" }).then((response) => {
        this.whList = response.data;
      });
    },
    getWH() {
      listInv0001({ parentId: "0", whType: "L" }).then((response) => {
        this.whList = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      viewById(row).then((response) => {
        this.form = response.data.invStockBill;
        this.itemList = response.data.invStockBillItemList;
        this.open = true;
        this.title = "修改盘点单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let para = {
            invStockBill: this.form,
            invStockBillItemList: this.itemList,
          };
          if (this.form.id != null) {
            updateStockbill(para).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStockbill(para).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除盘点单信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delStockbill(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/stockbill/export",
        {
          ...this.queryParams,
        },
        `stockbill_${new Date().getTime()}.xlsx`
      );
    },
    handleWHEdit() {
      this.form.vAreaId = null;
      this.form.vLocationId = null;
      this.localtionList = [];
      if (this.form.vWHId != "" && this.form.vWHId != "undefined") {
        listInv0001({ parentId: this.form.vWHId, whType: "L" }).then(
          (response) => {
            this.areaList = response.data;
          }
        );
      } else {
        this.areaList = [];
      }
    },
    handleAreaEdit() {
      this.form.vAreaId = this.form.vAreaId;
      this.form.vLocationId = "";
      this.localtionList = [];
      if (this.form.vAreaId != "" && this.form.vAreaId != "undefined") {
        listInv0001({ parentId: this.form.vAreaId, whType: "L" }).then(
          (response) => {
            this.localtionList = response.data;
          }
        );
      } else {
        this.form.vLocationId = null;
        this.itemList = [];
      }
    },

    addSpaList() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form.vLocationId = this.form.vLocationId.join(",");
          getInvDataList(this.form).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.itemList = response.data;
            // this.form.vLocationId = this.form.vLocationId.toString().split(",");
          });
        }
      });
    },

    handleStatusupdate(row, type) {
      row.status = type;
      updateBillStatus(row).then((response) => {
        this.getList();
      });
    },
    getNYkQty(row) {
      if (!!row.nActualQty) {
        return row.nActualQty - row.nInvQty - row.nChangeQty;
      } else {
        return null;
      }
    },
    handleEdit(index, row) {
      console.log(row);
      if (!!row.nActualQty) {
        row.nYKQty = row.nActualQty - row.nInvQty - row.nChangeQty;
      } else {
        row.nYKQty = row.nInvQty + row.nChangeQty;
      }
      console.log(this.itemList);
    },
    getCurrentDate() {
      const date = new Date();

      // 格式化日期为YYYY-MM-DD形式
      let year = date.getFullYear().toString();
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let day = date.getDate().toString().padStart(2, "0");

      // 更新currentDate变量值
      this.currentDate = `${year}-${month}-${day}`;
    },
  },
};
</script>
